<template>
    <basic-container>
        <!-- <avue-tabs :option="tabOption" @change="handleChange" v-model="selectTab"></avue-tabs> -->
        <ArrowLeftBold @click="initGoBackCase" width="24" height="24" style="padding-top: 4px; cursor: pointer"
            v-if="routerQuery.isCase" title="返回" />
        <el-tabs v-model="selectTab" class="demo-tabs" @tab-click="handleChange">
            <el-tab-pane :label="item.label" :name="item.prop" v-for="item in tabOption.column"
                :key="item.prop"></el-tab-pane>
        </el-tabs>
        <avue-crud :option="option" :table-loading="loading" :data="data" ref="crud" v-model="form"
            :permission="permissionList" :before-open="beforeOpen" v-model:page="page" @search-change="searchChange"
            @selection-change="selectionChange" @search-reset="searchReset" @current-change="currentChange"
            @size-change="sizeChange" @refresh-change="refreshChange" @row-save="rowSave" @row-update="rowUpdate"
            @row-del="rowDel" v-model:search="search">
            <template #menu-left v-if="!routerQuery.isCase">
                <!-- <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          v-if="permission.crf_delete"
          @click="handleDelete"
          >删 除
        </el-button> -->
                <!-- <el-button type="warning" plain icon="el-icon-download" @click="handleExport"
          >导 出
        </el-button> -->
            </template>
            <template #menu="{ row, index }">
                <div v-if="!routerQuery.isCase">
                    <el-button v-show="showButton(item, row)" v-for="item in menuList" :key="item.id" text
                        type="primary" :style="item.menuStyle" @click="handleMenu(item, row, index)">{{ item.text }}
                        <component :is="item.icon" class="btn-icon" v-if="item.status != row.status" />
                    </el-button>
                    <el-button v-show="selectTab === 1 && (item.id === '3' || item.id === '8')" v-for="item in menuList"
                        :key="item.id" text type="primary" :style="item.menuStyle"
                        @click="handleMenu(item, row, index)">{{ item.text }}
                    </el-button>
                    <el-button v-show="selectTab === 2 &&
                        (row.isShareBtn == '6'
                            ? item.id === '3' || item.id === '6' || item.id === '8'
                            : item.id === '3' || item.id === '8')
                        " v-for="item in menuList" :key="item.id" text type="primary" :style="item.menuStyle"
                        @click="handleMenu(item, row, index)">{{ item.text }}
                    </el-button>
                </div>
                <div v-else>
                    <el-button text type="primary" style="color: #0077bd" @click="handleSelect(row, index)">选 择
                    </el-button>
                </div>
            </template>
            <template #name="{ row, index }">
                <div style=" text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;"
                    :style="!routerQuery.isCase ? 'cursor: pointer;color: #3c8dbc' : ''"
                    @click="handleMenu({ id: '3' }, row, index)">
                    <span>{{ row.name }}</span>
                    <Lock style="width: 14px; height: 14px; margin-left: 5px; vertical-align: text-bottom;"
                        v-if="row.status == 2 && !routerQuery.isCase" />
                </div>
            </template>
            <template #isShareSelect="{ row }">
                <span :style="{
                    color:
                        row.isShareSelect === 1 ? '#0077bd' : row.isShareSelect === 2 ? '#398439' : '#fb9a00',
                }" style="font-weight: 550">{{ ['公开共享', '机构共享', '私有'][row.isShareSelect - 1] }}</span>
            </template>
        </avue-crud>
        <el-dialog v-model="isElectricityCaseDialog" title="添加备注" width="500">
            <div class="edit-dialog-content">
                <el-radio-group v-model="diagnoseRadio">
                    <el-radio value="1" border>首次诊断</el-radio>
                    <el-radio value="2" border>复 诊</el-radio>
                    <el-radio value="3" border>医 嘱</el-radio>
                    <el-radio value="4" border>检测报告</el-radio>
                    <el-radio value="5" border>其 他</el-radio>
                    <el-input v-if="diagnoseRadio === '5'" v-model="restInputValue" placeholder="请输入内容"></el-input>
                </el-radio-group>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="isElectricityCaseDialog = false">取 消</el-button>
                    <el-button type="primary" @click="dialogSubmit">确 定</el-button>
                </div>
            </template>
        </el-dialog>
    </basic-container>
</template>
<script setup>
import { findObject } from '@smallwei/avue';
import {
    getList,
    getDetail,
    add,
    update,
    remove,
    toShare,
    remark,
    lock,
    copy,
} from '@/api/crf/crf';
import opens from './components/opens.vue';
import institution from './components/institution.vue';
import privates from './components/privates.vue';
import { ref, reactive, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import { exportBlob } from '@/api/common';
import { getToken } from '@/utils/auth';
import { downloadXls } from '@/utils/util';
import { dateNow } from '@/utils/date';
import NProgress from 'nprogress';
import website from '@/config/website';
import 'nprogress/nprogress.css';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();
const crud = ref(null);
const store = useStore();
const backRoutesVal = computed(() => store.getters.backRoutesVal);
const tabOption = reactive({
    column: [
        {
            // icon: 'el-icon-info',
            label: '公开共享',
            prop: 1,
        },
        {
            label: '机构共享',
            prop: 2,
        },
        {
            label: '私有CRF',
            prop: 3,
        },
    ],
});
const selectTab = ref(1);
const routerQuery = ref({});
routerQuery.value = route.query;

const option = ref({
    height: 'auto',
    calcHeight: 30,
    tip: false,
    searchShow: true,
    border: true,
    index: true,
    selection: true,
    dialogClickModal: false,
    indexWidth: 80,
    indexLabel: '编号',
    menuWidth: 620,
    align: 'center',
    searchMenuSpan: 12,
    searchMenuPosition: 'right',
    dialogWidth: '30%',
    dialogCustomClass: 'crf-dialog',
    viewBtn: false,
    editBtn: false,
    delBtn: false,
    addBtn: false,
    refreshBtn: false,
    columnBtn: false,
    searchShowBtn: false,
    gridBtn: false,
    column: [
        {
            label: '主键',
            prop: 'id',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
        },
        {
            label: '租户ID',
            prop: 'tenantId',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
        },
        {
            label: '创建部门',
            prop: 'createDept',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
        },
        {
            label: '修改人',
            prop: 'updateUser',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
        },
        {
            label: '修改时间',
            prop: 'updateTime',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
        },
        {
            label: '状态',
            prop: 'status',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
        },
        {
            label: '是否已删除',
            prop: 'isDeleted',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
        },
        {
            label: 'CRF名称',
            prop: 'name',
            type: 'input',
            search: true,
            span: 24,
            slot: true,
            overHidden: true,
            width: 200,
            rules: [
                {
                    required: true,
                    message: '请输入CRF名称',
                    trigger: 'blur',
                },
            ],
        },
        {
            label: '量表类型',
            prop: 'lbType',
            type: 'select',
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=scale_type',
            props: {
                label: 'dictValue',
                value: 'dictKey',
            },
            filterable: true,
            overHidden: true,
            search: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: false,
        },
        {
            label: '创建人',
            prop: 'createUser',
            type: 'select',
            dicUrl: `/blade-system/user/all-user-list`,
            props: {
                label: 'realName',
                value: 'id',
            },
            filterable: true,
            overHidden: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
        },
        {
            label: '是否共享',
            prop: 'isShareSelect',
            type: 'select',
            slot: true,
            dicData: [
                {
                    label: '公开共享',
                    value: 1,
                },
                {
                    label: '机构共享',
                    value: 2,
                },
                {
                    label: '私 有',
                    value: 3,
                },
            ],
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: false,
        },
        {
            label: '创建时间',
            prop: 'createTime',
            type: 'input',
            overHidden: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
        },
        {
            label: '共享类型 1公开共享  2机构共享',
            prop: 'shareType',
            type: 'input',
            hide: true,
            overHidden: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
        },
        {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            minRows: 3,
            maxRows: 5,
            span: 24,
            overHidden: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: false,
        },
    ],
});
const form = ref({});
const query = ref({
    shareType: 1,
});
const search = ref({});
let loading = ref(false);
const page = ref({
    pageSize: 10,
    currentPage: 1,
    total: 0,
});
const selectionList = ref([]);
const data = ref([]);
const menuList = reactive([
    {
        text: '重命名',
        url: '',
        id: '1',
        status: 2,
        menuStyle: {
            color: '#fb9a00',
        },
    },
    {
        text: '设 计',
        url: '',
        id: '2',
        status: 2,
        menuStyle: {
            color: '#0077bd',
        },
    },
    {
        text: '试 用',
        url: '',
        id: '3',
        menuStyle: {
            color: '#00a65a',
        },
    },
    {
        text: '锁 定',
        url: '',
        id: '4',
        status: 2,
        menuStyle: {
            color: '#fb9a00',
        },
    },
    /* {
       text: 'OCR配置',
       url: '',
       id: '5',
       menuStyle: {
         color: '#00c0ef',
       },
     },*/
    {
        text: '公开共享',
        url: '',
        id: '6',
        menuStyle: {
            color: '#0077bd',
        },
    },
    {
        text: '机构共享',
        url: '',
        id: '7',
        menuStyle: {
            color: '#00a65a',
        },
    },
    {
        text: '复 制',
        url: '',
        id: '8',
        menuStyle: {
            color: '#fb9a00',
        },
    },
    // {
    //   text: '版本备份',
    //   url: '',
    //   id: '10',
    //   menuStyle: {
    //     color: '#00c0ef',
    //   },
    // },
    {
        text: '备 注',
        url: '',
        id: '9',
        menuStyle: {
            color: '#fb9a00',
        },
    },
    {
        text: '删 除',
        url: '',
        id: '10',
        menuStyle: {
            color: '#ff1c00',
        },
    },
    // {
    //   text: '',
    //   url: '',
    //   id: '11',
    //   icon: 'Microphone',
    //   menuStyle: {
    //     color: '#00a65a',
    //   },
    // },
    // {
    //   text: '',
    //   url: '',
    //   id: '12',
    //   icon: 'VideoCamera',
    //   menuStyle: {
    //     color: '#00a65a',
    //   },
    // },
]);
onMounted(() => {
    selectTab.value = store.state.common.selectTab || 1;
    initOptionBtn();
    TabRefreshChange();
});

// 计算属性：判断按钮是否显示
const showButton = computed(() => {
    return (item, row) => {
        if (selectTab.value !== 3) return false;
        if (item.status === row.status) return false;

        if (row.isShareBtn === '0') {
            return item.id !== '6' && item.id !== '7';
        } else if (row.isShareBtn === '6') {
            return item.id !== '7';
        } else {
            return item.status !== row.status;
        }
    };
});

// 获取 Vuex 中的 permission getter
const permission = computed(() => store.getters.permission);
const userInfo = computed(() => store.getters.userInfo);

// permissionList 计算属性
const validData = (value, defaultVal = false) => (value ? true : defaultVal);
const permissionList = computed(() => ({
    addBtn: validData(permission.value.crf_add, false),
    viewBtn: validData(permission.value.crf_view, false),
    delBtn: validData(permission.value.crf_delete, false),
    editBtn: validData(permission.value.crf_edit, false),
}));

// ids 计算属性
const ids = computed(() => {
    return selectionList.value.map(ele => ele.id).join(',');
});
const handleChange = tab => {
    selectTab.value = tab.props.name;
    // TabRefreshChange();
    store.commit('SET_TAB', selectTab.value);
    for (const key in search.value) {
        search.value[key] = '';
    }
    searchReset();
    initOptionBtn();
};
const initOptionBtn = () => {
    option.value.menuWidth = selectTab.value === 3 ? 620 : 200;

    const { column } = option.value;

    const name = findObject(column, 'name');
    const lbType = findObject(column, 'lbType');
    const isShareSelect = findObject(column, 'isShareSelect');
    const remark = findObject(column, 'remark');

    name.width = 200;
    lbType.hide = false;
    isShareSelect.hide = false;
    remark.hide = false;
    option.value.addBtn = true;

    if (routerQuery.value.isCase) {
        name.width = 500;
        lbType.hide = true;
        isShareSelect.hide = true;
        remark.hide = true;
        option.value.menuWidth = 200;
        option.value.addBtn = false;
    }
};
const rowSave = (row, done, loading) => {
    router.push({
        path: '/scaleTemplate/formDesign',
        query: {
            shareType: selectTab.value,
            name: row.name,
        },
    });
    done(row);
};
const handleMenu = (item, row, index) => {
    if (routerQuery.value.isCase) return;
    const { column } = option.value;
    const name = findObject(column, 'name');
    const remark = findObject(column, 'remark');

    const actions = {
        1: () => {
            name.editDisplay = true;
            crud.value.rowEdit(row, index);
        },
        4: () => posTlock(row),
        9: () => {
            remark.editDisplay = true;
            name.editDisplay = false;
            crud.value.rowEdit(row, index);
        },
        10: () => crud.value.rowDel(row, index),
        6: () => postToShare(row, '1'),
        7: () => postToShare(row, '2'),
        8: () => postCopy(row),
    };

    // 执行对应的操作
    if (actions[item.id]) actions[item.id]();

    // 处理路由跳转
    const pathList = {
        2: '/scaleTemplate/formDesign',
        3: '/scaleTemplate/formUse',
    };

    if (pathList[item.id]) {
        store.commit('SET_TAB', selectTab.value);
        router.push({
            path: pathList[item.id],
            query: { id: row.id },
        });
    }
};
let isElectricityCaseDialog = ref(false);
let diagnoseRadio = ref('1');
let restInputValue = ref('');
// 选择按钮点击
const handleSelect = (row, index) => {
    routerQuery.value.crfId = row.id;
    routerQuery.value.eleMedicalRecordName = row.name;
    if (routerQuery.value.isCase == '888') {
        initRouterCaseForm('检测报告')
    } else {
        isElectricityCaseDialog.value = true;
    }
};
// 添加备注弹窗点击事件
const dialogSubmit = () => {
    let remarkArr = ['首次诊断', '复 诊', '医 嘱', '检测报告', restInputValue.value];
    let caseName = remarkArr[Number(diagnoseRadio.value) - 1];
    if (diagnoseRadio.value === '5' && !restInputValue.value) {
        ElMessage.warning('请填写其他内容！');
        return;
    }
    initRouterCaseForm(caseName);
};
const initRouterCaseForm = (caseName) => {
    router.push({
        path: '/casemanagement/addCaseForm',
        query: {
            eleMedicalRecordRemark: caseName,
            eleMedicalRecordType: '3',
            ...routerQuery.value,
        },
    });
};
// 路由跳转到病历页面
const initGoBackCase = () => {
    routerQuery.value.selectTab = '2';
    delete routerQuery.value.eleMedicalRecordRemark;
    delete routerQuery.value.crfId;
    delete routerQuery.value.eleMedicalRecordName;
    delete routerQuery.value.isCase;
    router.replace({
        path: '/casemanagement/tabs',
        query: {
            ...routerQuery.value,
        },
    });
};
const postToShare = (row, shareType) => {
    postAction(
        `确定将该项数据进行${shareType === '1' ? '公开共享' : '机构共享'}？`,
        () => toShare({ id: row.id, shareType }),
        '共享成功!'
    );
};

const posTlock = row => {
    postAction('确定将该项数据进行锁定？', () => lock({ id: row.id }), '锁定成功!');
};

const postCopy = row => {
    postAction('确定将该项数据进行复制?', () => copy({ id: row.id }), '操作成功!');
};

const rowDel = (row, index, done) => {
    postAction('确定将选择数据删除?', () => remove(row.id), '操作成功!');
};

const postAction = (message, actionFn, successMessage) => {
    console.log(actionFn);
    ElMessageBox.confirm(message, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(actionFn)
        .then(() => {
            TabRefreshChange();
            ElMessage({ type: 'success', message: successMessage });
        });
};

const rowUpdate = (row, index, done, loading) => {
    update(row).then(
        () => {
            // onLoad(page.value);
            TabRefreshChange();
            ElMessage({
                type: 'success',
                message: '操作成功!',
            });
            done();
        },
        error => {
            loading();
            console.log(error);
        }
    );
};
const handleDelete = () => {
    if (selectionList.value.length === 0) {
        ElMessage.warning('请选择至少一条数据');
        return;
    }
    ElMessageBox.confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return remove(ids.value);
        })
        .then(() => {
            // onLoad(page.value);
            TabRefreshChange();
            ElMessage({
                type: 'success',
                message: '操作成功!',
            });
            crud.value.toggleSelection();
        });
};
const handleExport = () => {
    let downloadUrl = `/blade-crf/crf/export-crf?${website.tokenHeader}=${getToken()}`;
    const { name, lbType } = query.value;
    let values = {
        name_: name,
        lbType_: lbType,
    };
    ElMessageBox.confirm('是否导出数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        NProgress.start();
        exportBlob(downloadUrl, values).then(res => {
            downloadXls(res.data, `CRF管理${dateNow()}.xlsx`);
            NProgress.done();
        });
    });
};
const searchReset = () => {
    query.value = {};
    TabRefreshChange();
    // onLoad(page.value, query.value);
};
const searchChange = (params, done) => {
    query.value = params;
    page.value.currentPage = 1;
    TabRefreshChange();
    // onLoad(page.value, params);
    done();
};
const beforeOpen = (done, type) => {
    if (['edit', 'view'].includes(type)) {
        getDetail(form.value.id).then(res => {
            form.value = res.data.data;
        });
    }
    done();
};
const selectionChange = list => {
    selectionList.value = list;
};
const selectionClear = () => {
    selectionList.value = [];
    crud.value.toggleSelection();
};
const currentChange = currentPage => {
    page.value.currentPage = currentPage;
    TabRefreshChange();
};
const sizeChange = pageSize => {
    page.value.pageSize = pageSize;
    TabRefreshChange();
};
const refreshChange = () => {
    onLoad(page.value, query.value);
};
const TabRefreshChange = () => {
    query.value.shareType = null;
    if (selectTab.value === 1) {
        query.value.publicShare = '1';
    } else if (selectTab.value === 2) {
        query.value.deptShare = '1';
    }
    if (selectTab.value === 3) {
        query.value.create_user = userInfo.value.user_id;
    }
    onLoad(page.value, query.value);
};
const onLoad = (page, params = {}) => {
    loading.value = true;

    const { name, lbType } = query.value;

    let values = {
        name_: name,
        lbType_: lbType,
        descs: 'create_time',
        shareType: params.shareType || 1,
        ...params,
    };

    getList(page.currentPage, page.pageSize, values).then(res => {
        const DATA = res.data.data;
        page.total = DATA.total;
        data.value = DATA.records;
        data.value.forEach(item => {
            item.isShareSelect = 3;
            if (item.publicShare == '1') {
                item.isShareBtn = '0';
                item.isShareSelect = 1;
            } else if (item.deptShare == '1') {
                item.isShareBtn = '6';
                item.isShareSelect = 2;
            }
        });
        loading.value = false;
        selectionClear();
    });
};
</script>
<style lang="scss" scoped>
.btn-icon {
    width: 18px;
    height: 18px;
}

.crf-dialog {
    .el-dialog__body {
        overflow: hidden !important;
    }
}

.edit-dialog-content {
    width: 100%;
    height: auto;
    min-height: 150px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.edit-dialog-content {
    ::v-deep .el-radio-group {
        width: 170px;
        display: flex;
        flex-direction: column;
        align-items: flex-start;
    }

    ::v-deep .el-radio {
        margin-bottom: 10px;
    }
}
</style>
